package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
	"os/signal"

	"github.com/rocket049/easySecurityLink"
)

func msgProc(conn *easySecurityLink.ESLink) error {
	go func() {
		defer conn.Close()
		//读取标准输入，发送信息
		data := make([]byte, 4096)
		for {
			n, err := os.Stdin.Read(data)
			if n <= 0 {
				return
			}
			//fmt.Print(string(data))
			err = conn.Write("S", data[:n])
			if err != nil {
				return
			}
		}
	}()
	//读取并显示接受到的信息

	for {
		msg, err := conn.Read()
		if err != nil {
			return err
		}
		_, err = os.Stdout.Write(msg.Data)
		if err != nil {
			return err
		}
	}

	return nil
}

func server(port int) error {
	l, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port))
	if err != nil {
		return err
	}
	defer l.Close()
	c, err := l.Accept()
	if err != nil {
		return err
	}
	defer c.Close()
	conn, err := easySecurityLink.Upgrade(c)
	if err != nil {
		return err
	}
	defer conn.Close()
	go wait_sig(conn)
	return msgProc(conn)
}

func client(addr string) error {
	conn, err := easySecurityLink.Dial(addr)
	if err != nil {
		return err
	}
	defer conn.Close()
	go wait_sig(conn)
	return msgProc(conn)
}

func wait_sig(conn io.Closer) {
	var c chan os.Signal = make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	<-c
	conn.Close()
}

func main() {
	var listenPort = flag.Int("l", -1, "监听模式，参数为端口")
	flag.Parse()
	var err error
	if *listenPort <= 0 {
		//客户端模式
		err = client(flag.Arg(0))
	} else {
		err = server(*listenPort)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
	}
}
